﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace XChipUtils
{
    public class AppHelper : IAppHelper
    {

        //定义key地址
        private  uint keyBin = 0xfcfff021;
        /// <summary>
        /// 加密
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public  uint XorNotEncryption(string str)
        {
            uint temp = 0;
            uint data = Convert.ToUInt32(str, 16);
            temp = data ^ keyBin;
            return ~temp;
        }
        /// <summary>
        /// 解密
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public  uint XorNotDecryption(string str)
        {
            uint temp = 0;
            uint data = Convert.ToUInt32(str, 16);
            temp = (~data) ^ keyBin;
            return temp;
        }
        /// <summary>
        /// 字符串转UTF8
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public  string StringToUTF8(string str)
        {
            byte[] bytes = Encoding.UTF8.GetBytes(str);
            string hex = BitConverter.ToString(bytes).Replace("-", "");
            return hex;
        }
        /// <summary>
        /// UTF8转字符串
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public  string HexStringToString(string hex)
        {
            // 每两个字符表示一个字节，所以我们需要确保hex字符串长度是偶数  
            if (hex.Length % 2 != 0)
            {
                throw new ArgumentException("请输入正确的十六进制数据");
            }

            // 将hex字符串转换为字节数组  
            byte[] bytes = new byte[hex.Length / 2];
            for (int i = 0; i < hex.Length; i += 2)
            {
                bytes[i / 2] = Convert.ToByte(hex.Substring(i, 2), 16);
            }

            // 使用Encoding类将字节数组转换为字符串  
            return Encoding.UTF8.GetString(bytes); // 或者使用 Encoding.ASCII 如果它是ASCII编码的  
        }
        ///  <summary>
        ///  依据连接串名字connectionName返回数据连接字符串
        ///  </summary>
        ///  <param name="connectionName"></param>
        ///  <returns></returns>
        public  string GetConnectionStringsConfig(string connectionName)
        {
            string connectionString =
                    ConfigurationManager.ConnectionStrings[connectionName].ConnectionString.ToString();
            Console.WriteLine(connectionString);
            return connectionString;
        }

        ///  <summary>
        ///  更新连接字符串
        ///  </summary>
        ///  <param name="newName">  连接字符串名称  </param>
        ///  <param name="newConString">  连接字符串内容  </param>
        ///  <param name="newProviderName">  数据提供程序名称  </param>
        public  void UpdateConnectionStringsConfig(string newName,
            string newConString,
            string newProviderName)
        {
            bool isModified = false;    //  记录该连接串是否已经存在
                                        //  如果要更改的连接串已经存在
            if (ConfigurationManager.ConnectionStrings[newName] != null)
            {
                isModified = true;
            }
            //  新建一个连接字符串实例
            ConnectionStringSettings mySettings =
                new ConnectionStringSettings(newName, newConString, newProviderName);
            //  打开可执行的配置文件*.exe.config
            Configuration config =
                ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            //  如果连接串已存在，首先删除它
            if (isModified)
            {
                config.ConnectionStrings.ConnectionStrings.Remove(newName);
            }
            //  将新的连接串添加到配置文件中.
            config.ConnectionStrings.ConnectionStrings.Add(mySettings);
            //  保存对配置文件所作的更改
            config.Save(ConfigurationSaveMode.Modified);
            //  强制重新载入配置文件的ConnectionStrings配置节
            ConfigurationManager.RefreshSection("ConnectionStrings");
        }


        ///  <summary>
        ///  返回＊.exe.config文件中appSettings配置节的value项
        ///  </summary>
        ///  <param name="strKey"></param>
        ///  <returns></returns>
        public  string GetAppConfig(string strKey)
        {
            foreach (string key in ConfigurationManager.AppSettings)
            {
                if (key == strKey)
                {
                    return ConfigurationManager.AppSettings[strKey];
                }
            }
            return null;
        }

        ///  <summary>
        ///  在＊.exe.config文件中appSettings配置节增加一对键、值对
        ///  </summary>
        ///  <param name="newKey"></param>
        ///  <param name="newValue"></param>
        public  void UpdateAppConfig(string newKey, string newValue)
        {
            Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            if (config.AppSettings.Settings[newKey] != null)
            {
                config.AppSettings.Settings.Remove(newKey);
            }
            config.AppSettings.Settings.Add(newKey, newValue);
            config.Save(ConfigurationSaveMode.Modified);
            ConfigurationManager.RefreshSection("appSettings");
        }

        /// <summary>
        /// 获取时间戳
        /// </summary>
        /// <returns></returns>
        public  string GetTimeStamp()
        {
            TimeSpan ts = DateTime.Now - new DateTime(1970, 1, 1, 0, 0, 0, 0);
            return Convert.ToInt64(ts.TotalSeconds).ToString();
        }


        /// <summary>
        /// 清理文件
        /// </summary>
        /// <param name="v"></param>
        /// <param name="isbool"></param>
        public  void ClearFileToPath(string v, bool isbool)
        {
            //setShowMsg($"清理文件---》》》》开始");

            DirectoryInfo folder = new DirectoryInfo(v);
            foreach (DirectoryInfo file in folder.GetDirectories())
            {
                if (isbool)
                {
                    if (DateTime.Compare(file.CreationTime, DateTime.Now.AddDays(-7)) < 0 && file.FullName.Contains($"Bin{DateTime.Now.AddDays(-7).ToString("yyyyMM")}"))
                    {
                        Directory.Delete(file.FullName, true);
                    }
                }
                else
                {
                    if (file.FullName.Contains($"Bin{DateTime.Now.ToString("yyyy")}"))
                    {
                        Directory.Delete(file.FullName, true);
                    }
                }

            }
            IFileHelper fileHelper = new GenerateFileHelp();
            var pathList = fileHelper.GetFileTimePath(v, "*.txt");
            var pathList2 = fileHelper.GetFileTimePath(v, "*.bin");
            foreach (KeyValuePair<string, DateTime> item in pathList)
            {
                if (isbool)
                {
                    if (DateTime.Compare(item.Value, DateTime.Now.AddDays(-7)) < 0 && (item.Key.Contains(".txt")))
                    {
                        if (!item.Key.Contains("reset") && !item.Key.Contains("save_exit") && !item.Key.Contains("说明文档") && !item.Key.Contains("readme")) //需要过滤文件
                        {
                            File.Delete(item.Key);
                        }
                    }
                }
                else
                {


                    if (!item.Key.Contains("reset") && !item.Key.Contains("save_exit") && !item.Key.Contains("说明文档") && !item.Key.Contains("readme"))
                    {
                        File.Delete(item.Key);
                    }
                }

            }

            foreach (KeyValuePair<string, DateTime> item in pathList2)//删除安装目录下bin文件
            {
                if (isbool)
                {


                    if (DateTime.Compare(item.Value, DateTime.Now.AddDays(-7)) < 0)
                    {
                        File.Delete(item.Key);
                    }
                }
                else
                {
                    File.Delete(item.Key);
                }

            }
            // setShowMsg($"清理文件《《《《---结束");
        }



        public  string NameTypeToString(string str)
        {
            string nameT = str.ToLower();
            string[] patterns = { "_h", "_l", "m0", "m1", "m2", "m3", "m4", "m5", "m6", "m7", "en", "_long", "_short", "_veryshort", "_day", "_day_set", "_night", "_night_set", "_midnight", "_color", "_gray" };

            foreach (var pattern in patterns)
            {
                //if (nameT.EndsWith(pattern))
                //{
                //    //nameT = nameT.Replace(pattern, "");
                    
                //}
                if (nameT.EndsWith(pattern))
                {
                    nameT = nameT.Substring(0, nameT.Length - pattern.Length);
                    break;
                }
            }
            //在多复制一次防止出现XXX_day_h,XXX_h_day的情况
            foreach (var pattern in patterns)
            {
                if (nameT.EndsWith(pattern))
                {
                    nameT = nameT.Substring(0, nameT.Length - pattern.Length);
                    break;
                }
            }

            return nameT;
        }

    }
}
